<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin;

use App\Middleware\JwtMiddleware;
use App\Middleware\ManagerRights;
use App\Model\Manager;
use App\Resource\ManagerCollection;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;

#[Controller]
class ManagerController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected RequestInterface $request;

    #[RequestMapping(path: "login", methods: "post")]
    /**
     * 登录
     * @return false|string
     */
    public function login()
    {
        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'username' => 'required',
                'password' => 'required',
            ],
            [
                'username.required' => '请填写用户名',
                'password.required' => '请填写登录密码'
            ]
        );

        $data = $data->validated();

        /** @var Manager $manager */
        $manager = Manager::getByUsername($data['username']);
        if (!$manager) {
            return self::jsonResponse(404, '用户不存在');
        }

        if (!$manager->checkPwd($data['password'])) {
            return self::jsonResponse(400, '用户名或密码错误');
        }

        if ($manager->status != 1) {
            return self::jsonResponse(400, '用户被禁止登录');
        }

        //JWT登录创建token
        $token = auth('manager')->login($manager);

        $data = [
            'token' => $token,
            'token_type' => 'bearer',
            'manager' => $manager->toApi(),
        ];

        return self::jsonResponse(200, 'success', $data);
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "", methods: "get")]
    /**
     * 列表
     * @return false|string
     */
    public function list()
    {
        $list = Manager::query();
        if ($status = $this->request->input('status')) {
            $list->where('status', $status);
        }

        if ($keyword = $this->request->input('keyword')) {
            $list->keyword($keyword);
        }

        if ($roleId = $this->request->input('role_id')) {
            $list->where('role_id', $roleId);
        }

        $list = $list->paginate((integer)$this->request->input('page_num'));

        $data = [
            'list' => (new ManagerCollection($list))->toListApi(),
            'count' => $list->total(),
            'count_page' => $list->lastPage(),
            'page_num' => $list->perPage(),
        ];
        return self::jsonResponse(200, 'success', $data);
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "detail", methods: "get")]
    /**
     * 用户详情
     * @return false|string
     */
    public function detail()
    {
        $id = $this->request->input('id');
        /** @var Manager $manager */
        $manager = Manager::getById($id);
        if (!$manager) {
            return self::jsonResponse(404, '管理员不存在');
        }
        return self::jsonResponse(200, 'success', $manager->toApi());
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "handle", methods: "post")]
    /**
     * 启用/禁用
     * @return false|string
     */
    public function handle()
    {
        $id = $this->request->input('id');
        /** @var Manager $manager */
        $manager = Manager::getById($id);
        if (!$manager) {
            return self::jsonResponse(404, '管理员不存在');
        }

        $manager->handle();
        $manager->save();

        return self::jsonResponse(200, 'success');
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "delete", methods: "delete")]
    /**
     * 删除
     * @return false|string
     * @throws \Exception
     */
    public function delete()
    {
        $id = $this->request->input('id');
        /** @var Manager $manager */
        $manager = Manager::getById($id);
        if (!$manager) {
            return self::jsonResponse(404, '管理员不存在');
        }

        $manager->delete();
        return self::jsonResponse(200, 'success');
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "edit", methods: "post")]
    /**
     * 编辑
     * @return false|string
     */
    public function edit()
    {
        $id = $this->request->input('id');
        /** @var Manager $manager */
        $manager = Manager::getById($id);
        if (!$manager) {
            return self::jsonResponse(404, '管理员不存在');
        }
        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'name' => '',
                'username' => [
                    'required',
                    Rule::unique('manager')->where(function ($q) use ($manager) {
                        $q->whereNull('delete_time')->where('id', '!=', $manager->id);
                    })
                ],
                'mobile' => [
                    'nullable',
                    Rule::unique('manager')->where(function ($q) use ($manager) {
                        $q->whereNull('delete_time')->where('id', '!=', $manager->id);
                    })
                ],
                'email' => '',
                'role_id' => ''
            ],
            [
                'username.required' => '请填写用户名',
                'username.unique' => '用户名已存在',
                'mobile.unique' => '联系方式已存在',
            ]
        );

        if ($data->fails()) {
            return self::jsonResponse(422, $data->errors()->first());
        }

        $data = $data->validated();
        $manager->fill($data);
        $manager->save();

        return self::jsonResponse(200, 'success');
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "add", methods: "post")]
    /**
     * 添加
     * @return false|string
     */
    public function add()
    {
        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'name' => '',
                'username' => [
                    'required',
                    Rule::unique('manager')->where(function ($q) {
                        $q->whereNull('delete_time');
                    })
                ],
                'password' => 'required',
                'mobile' => [
                    'nullable',
                    Rule::unique('manager')->where(function ($q) {
                        $q->whereNull('delete_time');
                    })
                ],
                'email' => '',
                'role_id' => ''
            ],
            [
                'username.required' => '请填写用户名',
                'password.required' => '请填写登录密码',
                'username.unique' => '用户名已存在',
                'mobile.unique' => '联系方式已存在',
            ]
        );

        if ($data->fails()) {
            return self::jsonResponse(422, $data->errors()->first());
        }

        $data = $data->validated();

        $manager = new Manager($data);
        $manager->save();

        return self::jsonResponse(200, 'success');
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "changePwd", methods: "post")]
    /**
     * 修改密码
     * @return false|string
     */
    public function changePwd()
    {
        /** @var Manager $manager */
        $manager = auth('manager')->user();
        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'old_password' => 'required',
                'password' => 'required|confirmed',
            ],
            [
                'old_password.required' => '请填写旧密码',
                'password.required' => '请填写新密码',
                'password.confirmed' => '两次密码不一致',
            ]
        );

        if ($data->fails()) {
            return self::jsonResponse(422, $data->errors()->first());
        }

        $data = $data->validated();

        if (!$manager->checkPwd($data['old_password'])) {
            return self::jsonResponse(400, '旧密码不正确');
        }

        $manager->password = $data['password'];
        $manager->save();

        return self::jsonResponse();
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "resetPwd", methods: "post")]
    /**
     * 重置密码
     * @return false|string
     */
    public function resetPwd()
    {
        $id = $this->request->input('id');
        /** @var Manager $manager */
        $manager = Manager::getById($id);
        if (!$manager) {
            return self::jsonResponse(404, '管理员不存在');
        }

        $password = $this->request->input('password');
        if (!$password) {
            return self::jsonResponse(422, '请填写新密码');
        }

        $manager->password = $password;
        $manager->save();

        return self::jsonResponse();
    }

    /**
     * 返回统一json
     * @param int $status
     * @param $message
     * @param $data
     * @param $headerStatus
     * @return false|string
     */
    public static function jsonResponse(int $status = 200, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
